import entity.User;
import mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by yiyongyao on 2018/3/1.
 */
public class controller {


    public static void main(String[] args) throws IOException {
        // xml构建sessionfactory
        testOne();
        //非xml构建sessionfactory
        testTwo();

    }

    private static void testTwo() throws IOException {

        String source = "mybatis/mybatiscfg.xml";
        InputStream inputStream = Resources.getResourceAsStream(source);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        User liUser = new User();
        liUser.setUsername("lisi");
        liUser.setPassword("123654");
        liUser.setRoleType(2);
        liUser.setAddress("辽宁省大连市");

        UserMapper userMapper = session.getMapper(UserMapper.class);
        //userMapper.add(liUser);
        User zhang = userMapper.selectByName("zhangsan");
        System.out.println(zhang.getUsername() + ": from " + zhang.getAddress());
    }


    public static void testOne() throws IOException {

        String source = "mybatis/mybatiscfg.xml";
        InputStream inputStream = Resources.getResourceAsStream(source);
        //应用作用域
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //请求作用域
        SqlSession session = sqlSessionFactory.openSession();
        User liUser = new User();
        liUser.setUsername("lisi");
        liUser.setPassword("123654");
        liUser.setRoleType(2);
        liUser.setAddress("辽宁省大连市");
        int result = session.insert("mapper.UserMapper.add", liUser);
        session.commit();
        System.out.println(result);
        User zhang = session.selectOne("mapper.UserMapper.selectByName", "lisi");
        System.out.println(zhang.getUsername() + ": from " + zhang.getAddress());
        session.close();
    }

}
